<template>
  <div>
    <a-upload
      name="files"
      :multiple="true"
      :headers="this.token"
      :fileList="fileListData"
      :beforeUpload="beforeUpload"
      :action="uploadService"
      @change="handleChange"
    >
      <a-button> <a-icon type="upload" /> 上传 </a-button>
    </a-upload>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { getToken } from "@/utils/token";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  props: ["imgURL"],
  data() {
    return {
      token: { token: getToken() },
      uploadService: this.$globalConfig.uploadService + "/base/upload", //上传服务器地址
      uploadPath: this.$globalConfig.uploadPath + "/file/", // 图片路径服务器地址
      previewVisible: false,
      fileList: [],
      fileListData: []
      // fileListData: [
      //   {
      //     uid: "-1",
      //     name: "xxx.png",
      //     status: "done",
      //     url: "http://www.baidu.com/xxx.png"
      //   }
      // ]
    };
  },
  methods: {
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        this.$message.error("文件超过50M了");
      }
      return isLt50M;
    },
    handleChange({ file, fileList }) {
      console.log(file.status);
      if (
        file.status !== "removed" &&
        file.response &&
        file.response.status !== 200
      ) {
        this.$message.error("上传失败，检查服务是否正常或者重新上传");
        return;
      }
      if (file.status === "removed") {
        this.fileListData = fileList;
        this.fileList = this.fileListMap(this.fileListData);
      }
      if (file.status === "uploading" && file.size / 1024 / 1024 < 50) {
        this.fileListData = fileList;
      }
      if (file.status === "done" && file.response.status === 200) {
        this.fileList = this.fileListMap(this.fileListData);
      }
      // debugger
    },
    fileListMap(fileListData) {
      let datas = [];
      for (let item of fileListData) {
        let items = {};
        if (item.response && item.response.status === 200) {
          items.name = item.name;
          items.data = item.response.data[0];
          datas.push(items);
        }
      }
      return datas;
    },
    handleCancel() {
      this.previewVisible = false;
    }
  },
  created() {}
};
</script>

<style scoped lang="less"></style>
